package com.jxwifi.cloud.quickclean.okhttp;

import com.idroid.utils.Pools;
import com.lidroid.util.Logger;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * 下载的callback
 * Created by zhuheyong on 2016/8/31.
 */
public class DownLoadCallback implements Callback {

    private DownLoadCallBackListener mCB;

    private DownLoadCallback(DownLoadCallBackListener DownLoadCallBackListener) {
        mCB = DownLoadCallBackListener;
    }

    public void setRespondCallBack(DownLoadCallBackListener DownLoadCallBackListener) {
        mCB = DownLoadCallBackListener;
    }


    private static final Pools.SimplePool<DownLoadCallback> sPool = new Pools.SimplePool<DownLoadCallback>(10);

    public static DownLoadCallback obtain(DownLoadCallBackListener responseCallback) {
        DownLoadCallback instance = sPool.acquire();
        if (instance != null) {
            instance.setRespondCallBack(responseCallback);
            return instance;
        } else {
            return new DownLoadCallback(responseCallback);
        }
    }

    public void recycle() {
        // Clear state if needed.
        mCB = null;
        sPool.release(this);
    }

    @Override
    public void onFailure(Call call, IOException e) {
        if (!"Canceled".equalsIgnoreCase(e.getMessage()) && !"Socket closed".equalsIgnoreCase(e.getMessage()))
            OkHttp.uiHandler.post(new Runnable() {
                @Override
                public void run() {
                    DownLoadCallBackListener callback = mCB;
                    recycle();
                    if (callback != null)
                        callback.onFailure(-11, "网络故障，请检查网络!");

                }
            });
        else
            recycle();
    }

    @Override
    public void onResponse(Call call, Response response) {
        DownLoadCallBackListener callback = mCB;
        recycle();
        if (callback != null)
            callback.onResponse(response);
        else
            Logger.e("找不到回调了");
    }

    public interface DownLoadCallBackListener {

        void onResponse(Response response);

        void onFailure(int ErrorCode, String msg);

    }

}
